package com.hrg.rds.infra.connect.protocol.modbus;

import com.hrg.rds.infra.connect.ConnectionHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.plc4x.java.api.PlcConnection;
import org.apache.plc4x.java.api.PlcConnectionManager;
import org.apache.plc4x.java.utils.cache.CachedPlcConnectionManager;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class ModbusConnectionHolder implements ConnectionHolder {

	private final ModbusProperties modbusProperties;
	private final Map<String, PlcConnectionManager> map = new HashMap<>();

	ModbusConnectionHolder(ModbusProperties modbusProperties) {
		this.modbusProperties = modbusProperties;
		for (ModbusProperties.ModbusProperty modbusProperty : modbusProperties.getConnections()) {
			String connId = modbusProperty.getConnId();
			PlcConnectionManager connectionManager = CachedPlcConnectionManager.getBuilder()
					//maxLeaseTime 默认4s,线程可以拥有该连接的最大时长，超过后线程不能再使用，会被cache终止租约
					.withMaxLeaseTime(Duration.ofMillis(modbusProperty.getMaxLeaseTime()))
					// maxWaitTime 默认20s，线程申请的最大等待时长，超过后cache抛出异常PlcConnectionException
					.withMaxWaitTime(Duration.ofMillis(modbusProperty.getMaxWaitTime()))
					.build();
			map.put(connId, connectionManager);
		}
	}

	@Override
	public PlcConnection getConnection(String connId) throws Exception {
		return getConnection(map.get(connId), connId);
	}
}
